package mephisto.services.impl;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import mephisto.Constants;
import mephisto.services.IRdfService;
import mephisto.services.IServiceProxy;

import org.json.JSONArray;
import org.json.JSONObject;
import org.restlet.ext.json.JsonRepresentation;

//registerNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
//registerNamespace("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
//registerNamespace("bom", "http://www.ifi.unizh.ch/ddis/evoont/2008/11/bom#");
//registerNamespace("xsd", "http://www.w3.org/2001/XMLSchema#");
//registerNamespace("foaf", "http://xmlns.com/foaf/0.1/");
//registerNamespace("wf", "http://www.w3.org/2005/01/wf/flow#");
//registerNamespace("mephisto", "http://mephistopedia.net/2009/03/14/mephisto#");


public class RdfServiceProxy extends BaseService implements IRdfService, IServiceProxy {

    Map<String, String> namespaces = new HashMap<String, String>();
    String endpoint = null;

    public RdfServiceProxy() {
        super();
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }
    
    public Object runQuery(String sparql) {
        return runQuery(sparql, false);
    }

    public JSONArray runQuery(String sparql, boolean flag) {
        
        try {
        sparql = getNamespacePrefix() + sparql;

        String user = mephisto.get(Constants.RDF_SERVICE_USER);
        String password = mephisto.get(Constants.RDF_SERVICE_PASSWORD);

        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("query", sparql);
        parameters.put("format", "json");
        parameters.put(Constants.USER, user);
        parameters.put(Constants.PASSWORD, password);
        HttpCallHandler hch = new HttpCallHandler();
        InputStream is = hch.callBasicAuthService(parameters, endpoint);
        String output = Utils.streamToString(is);
        
        JsonRepresentation json = new JsonRepresentation(output);
        JSONObject object = json.toJsonObject();
        JSONObject results = object.getJSONObject("results");
        JSONArray bindings = results.getJSONArray("bindings");
        
        return bindings;
        
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONArray();
        }
        
        

    }

    public String getNamespacePrefix() {
        StringBuffer sb1 = new StringBuffer();
        Iterator<String> it = namespaces.keySet().iterator();
        while (it.hasNext()) {
            Object key = it.next();
            String namespace = namespaces.get(key);
            sb1.append("prefix " + key + ":" + "<" + namespace + ">\n");

        }

        return sb1.toString();
    }

    public String addMissingNamespaces(String input) {
        if (input.indexOf("http") == 0 || input.indexOf("ftp") == 0 || input.indexOf("<") == 0)
            return input;

        Iterator keyIt = namespaces.keySet().iterator();
        while (keyIt.hasNext()) {
            Object key = keyIt.next();
            String namespace = (String) namespaces.get(key);
            if (input.indexOf(key + ":") == 0)
                ;
            input = input.replaceAll(key + ":", namespace);
        }
        return input;

    }

    public boolean isLiteral(String input) {
        if (input.indexOf("http") == 0 || input.indexOf("ftp") == 0)
            return false;
        Iterator keyIt = namespaces.keySet().iterator();
        while (keyIt.hasNext()) {

            Object key = keyIt.next();
            if (input.indexOf(key + ":") == 0)
                return false;

        }

        return true;

    }

    public String cleanNamespaces(String rel) {
        if (rel == null)
            return null;

        Iterator<String> keyIt = namespaces.keySet().iterator();
        while (keyIt.hasNext()) {
            Object key = keyIt.next();
            String namespace = (String) namespaces.get(key);
            rel = rel.replaceAll(namespace, key + ":");
        }
        return rel;

    }

    public String printResults(List list) {

        StringBuffer sb = new StringBuffer();
        if (list != null && list.size() > 0) {
            sb.append("!!Results !! \n");
            Iterator it = list.iterator();
            while (it.hasNext()) {
                Map entry = (Map) it.next();
                Iterator it2 = entry.keySet().iterator();
                while (it2.hasNext()) {
                    Object key2 = it2.next();
                    Map entry2 = (Map) entry.get(key2);
                    Object value2 = entry2.get("value");
                    sb.append("::" + key2 + " :: " + value2 + "\n");
                }

            }
        }
        return sb.toString();
    }
    
    public String registerNamespace(String name, String namespace) {
        return namespaces.put(name, namespace);
    }



}
